package kr.hkit.androidcomplete01.ch19;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class LongTime5 extends Activity {

	int mValue;
	TextView mText;
	ProgressDialog mProgress;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_longtime2);
		mText = (TextView) findViewById(R.id.text);
	}

	public void mOnClick(View v) {
		new AccumulateTask().execute(100);
	}

	class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
		protected void onPreExecute() {
			mProgress = new ProgressDialog(LongTime5.this);
			mProgress.setTitle("Updating");
			mProgress.setMessage("Wait...");
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setCancelable(true);
			mProgress.setProgress(mValue);
			mProgress.setOnCancelListener(new OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					cancel(true);
				}
			});
			mProgress.show();
		}

		protected void onPostExecute(Integer result) {
			mProgress.dismiss();
			mValue = 0;
		}

		protected void onCancelled() {
			mProgress.dismiss();
		}
		

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mText.setText(values[0]+"");
			mProgress.setProgress(mValue);
		}

		protected Integer doInBackground(Integer... params) {
			while (isCancelled() == false) {
				mValue++;
				if (mValue < params[0] + 1)
					publishProgress(mValue);
				else
					break;
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}
			}
			return mValue;
		}
	}
}
